package com.yun.datastructure.tree.binarytree.leetcode;

import com.yun.datastructure.tree.binarytree.domain.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Leetcode145 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(
                new TreeNode(new TreeNode(4), 2, null),
                1,
                new TreeNode(new TreeNode(5), 3, new TreeNode(6))
        );
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<TreeNode> stack = new LinkedList<>();
        List<Integer> result=new ArrayList<>();
        TreeNode curr = root;
        TreeNode pop = null;
        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                stack.push(curr);
                //待处理左子树
                curr = curr.left;
            } else {
                TreeNode peek = stack.peek();
                //没有右子树
                if (peek.right == null) {
                    pop = stack.pop();
                    result.add(pop.val);
                }
                //右子树处理完成
                else if (peek.right == pop) {
                    pop = stack.pop();
                    result.add(pop.val);
                }
                //处理右子树
                else {
                    curr = peek.right;
                }
            }
        }
        return result;
    }

}
